import React from 'react';
import {
  Clock,
  CheckCircle,
  ChevronRight,
  BookOpen,
  Eye,
  Home,
  BookPlus
} from 'lucide-react';
import { Quiz, Question } from '../../types';
import { Layout } from '../components/Layout';
import { QuestionNav } from '../components/QuestionNav';
import { ScoreData } from '../utils/scoreCalculator';

interface ExamRunningViewProps {
  quiz: Quiz;
  activeQuestionIndex: number;
  userAnswers: Map<string, string | string[]>;
  isReview: boolean;
  elapsedTime?: number;
  scoreData?: ScoreData;
  onAnswer: (qId: string, value: string, isMulti: boolean) => void;
  onSubmit: () => void;
  onHomeClick: () => void;
  onBackToResult?: () => void;
  onQuestionChange: (index: number) => void;
  onSettingsClick: () => void;
  onAddToMistake?: (question: Question) => void;
  formatTime: (seconds: number) => string;
  sidebarContent: React.ReactNode;
}

export const ExamRunningView: React.FC<ExamRunningViewProps> = ({
  quiz,
  activeQuestionIndex,
  userAnswers,
  isReview,
  elapsedTime = 0,
  scoreData,
  onAnswer,
  onSubmit,
  onHomeClick,
  onBackToResult,
  onQuestionChange,
  onSettingsClick,
  onAddToMistake,
  formatTime,
  sidebarContent
}) => {
  const question = quiz.questions[activeQuestionIndex];
  const isMulti = Array.isArray(question.correctAnswer);

  // Result status map for review mode sidebar
  const resultStatuses = isReview && scoreData
    ? scoreData.results.reduce((acc: any, r) => ({ ...acc, [r.id]: r.isCorrect }), {})
    : undefined;

  return (
    <Layout
      onSettingsClick={onSettingsClick}
      onHomeClick={onHomeClick}
      sidebarContent={
        <QuestionNav
          questions={quiz.questions}
          activeId={question.id}
          onClick={onQuestionChange}
          statuses={resultStatuses}
          userAnswers={userAnswers}
        />
      }
    >
      <div className="flex flex-col h-full">
        {/* Header */}
        <header className="relative flex items-center justify-between px-8 py-4 bg-white border-b border-slate-200">
          <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 font-bold text-lg text-slate-800">
            {quiz.title}
          </div>
          <div className="flex items-center gap-4">
            <span className="bg-slate-100 text-slate-600 px-3 py-1 rounded-full text-sm font-medium">
              第 {activeQuestionIndex + 1} 题 / 共 {quiz.questions.length} 题
            </span>
            <span
              className={`text-xs font-bold px-2 py-0.5 rounded uppercase tracking-wider ${
                question.type === 'judge'
                  ? 'bg-orange-100 text-orange-700'
                  : 'bg-blue-100 text-blue-700'
              }`}
            >
              {question.type === 'choice'
                ? isMulti
                  ? '多项选择'
                  : '单项选择'
                : '判断题'}
            </span>
          </div>
          <div className="flex items-center gap-6">
            {!isReview && (
              <div className="flex items-center gap-2 text-slate-600 font-mono text-lg bg-slate-50 px-3 py-1 rounded-lg">
                <Clock className="w-4 h-4" />
                {formatTime(elapsedTime)}
              </div>
            )}
            {isReview && (
              <div className="flex items-center gap-2 bg-slate-100 text-slate-600 px-3 py-1 rounded-lg text-sm font-medium">
                <Eye className="w-4 h-4" />
                复习模式
              </div>
            )}

            {!isReview && (
              <button
                onClick={onSubmit}
                className="bg-primary hover:bg-indigo-700 text-white px-6 py-2 rounded-lg text-sm font-bold shadow-md shadow-primary/20 transition-all"
              >
                提交试卷
              </button>
            )}
            {isReview && (
              <div className="flex items-center gap-3">
                <button
                  onClick={onHomeClick}
                  className="flex items-center gap-2 text-slate-500 hover:text-slate-800 text-sm font-medium px-4 py-2 rounded-lg hover:bg-slate-100 transition-colors"
                >
                  <Home className="w-4 h-4" />
                  返回首页
                </button>
                <button
                  onClick={onBackToResult}
                  className="bg-indigo-50 hover:bg-indigo-100 text-primary hover:text-indigo-700 text-sm font-medium px-4 py-2 rounded-lg transition-all"
                >
                  返回成绩单
                </button>
              </div>
            )}
          </div>
        </header>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-8 bg-slate-50/50">
          <div className="max-w-3xl mx-auto">
            <div className="bg-white p-8 rounded-2xl shadow-sm border border-slate-100 min-h-[400px]">
              <h3 className="text-2xl font-medium text-slate-800 leading-relaxed mb-8">
                {question.title}
              </h3>

              <div className="space-y-3">
                {question.type === 'judge' ? (
                  ['true', 'false'].map((opt) => {
                    const isSelected = userAnswers.get(question.id) === opt;
                    const optText = opt === 'true' ? '正确 (True)' : '错误 (False)';

                    // Review styles
                    let itemClass =
                      'flex items-center gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all ';
                    if (isReview) {
                      if (opt === String(question.correctAnswer))
                        itemClass += 'border-green-500 bg-green-50 ';
                      else if (isSelected && opt !== String(question.correctAnswer))
                        itemClass += 'border-red-500 bg-red-50 ';
                      else itemClass += 'border-slate-100 opacity-50 ';
                    } else {
                      itemClass += isSelected
                        ? 'border-primary bg-indigo-50'
                        : 'border-slate-100 hover:border-slate-200 hover:bg-slate-50';
                    }

                    return (
                      <div
                        key={opt}
                        onClick={() => !isReview && onAnswer(question.id, opt, false)}
                        className={itemClass}
                      >
                        <div
                          className={`w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all ${
                            isSelected || (isReview && opt === String(question.correctAnswer))
                              ? isReview && opt === String(question.correctAnswer)
                                ? 'border-green-500'
                                : 'border-primary'
                              : 'border-slate-300'
                          }`}
                        >
                          {(isSelected ||
                            (isReview && opt === String(question.correctAnswer))) && (
                            <div
                              className={`w-3 h-3 rounded-full ${
                                isReview && opt === String(question.correctAnswer)
                                  ? 'bg-green-500'
                                  : 'bg-primary'
                              }`}
                            />
                          )}
                        </div>
                        <span className="text-lg text-slate-700 font-medium">{optText}</span>
                      </div>
                    );
                  })
                ) : (
                  question.options?.map((opt, idx) => {
                    const optLabel = String.fromCharCode(65 + idx); // A, B, C...
                    const currentAns = userAnswers.get(question.id);
                    const isSelected = isMulti
                      ? (currentAns as string[] || []).includes(optLabel)
                      : currentAns === optLabel;

                    // Review Logic
                    const isActualCorrect = isMulti
                      ? (question.correctAnswer as string[]).includes(optLabel)
                      : question.correctAnswer === optLabel;

                    let itemClass =
                      'flex items-center gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all ';
                    if (isReview) {
                      if (isActualCorrect) itemClass += 'border-green-500 bg-green-50 ';
                      else if (isSelected && !isActualCorrect)
                        itemClass += 'border-red-500 bg-red-50 ';
                      else itemClass += 'border-slate-100 opacity-50 ';
                    } else {
                      itemClass += isSelected
                        ? 'border-primary bg-indigo-50'
                        : 'border-slate-100 hover:border-slate-200 hover:bg-slate-50';
                    }

                    return (
                      <div
                        key={idx}
                        onClick={() => !isReview && onAnswer(question.id, optLabel, isMulti)}
                        className={itemClass}
                      >
                        <div
                          className={`w-8 h-8 shrink-0 rounded-lg border-2 flex items-center justify-center font-bold transition-all ${
                            isSelected || (isReview && isActualCorrect)
                              ? isReview && isActualCorrect
                                ? 'border-green-500 text-green-600'
                                : 'border-primary text-primary'
                              : 'border-slate-200 text-slate-400'
                          }`}
                        >
                          {optLabel}
                        </div>
                        <span className="text-lg text-slate-700">{opt}</span>
                      </div>
                    );
                  })
                )}
              </div>

              {isReview && (
                <div className="mt-8 p-6 bg-slate-50 rounded-xl border border-slate-200 animate-in fade-in slide-in-from-top-4">
                  <h4 className="text-sm font-bold text-slate-900 uppercase tracking-wider mb-2 flex items-center gap-2">
                    <BookOpen className="w-4 h-4" /> 答案解析
                  </h4>
                  <p className="text-slate-600 leading-relaxed">{question.explanation}</p>
                  <div className="mt-2 text-sm text-slate-500">
                    <span className="font-medium text-slate-700">正确答案: </span>
                    {Array.isArray(question.correctAnswer)
                      ? JSON.stringify(question.correctAnswer)
                      : question.correctAnswer}
                  </div>
                </div>
              )}
            </div>

            {/* Navigation Footer */}
            <div className="flex justify-between mt-6 items-center">
              <button
                disabled={activeQuestionIndex === 0}
                onClick={() => onQuestionChange(activeQuestionIndex - 1)}
                className="text-slate-500 hover:text-slate-800 disabled:opacity-30 disabled:hover:text-slate-500 font-medium px-4 py-2"
              >
                上一题
              </button>

              {isReview && onAddToMistake && (
                <button
                  onClick={() => onAddToMistake(question)}
                  className="flex items-center gap-2 text-amber-600 hover:text-amber-700 bg-amber-50 hover:bg-amber-100 text-sm font-medium px-4 py-2 rounded-lg transition-colors"
                >
                  <BookPlus className="w-4 h-4" />
                  添加到题集
                </button>
              )}

              {activeQuestionIndex === quiz.questions.length - 1 && !isReview ? (
                <button
                  onClick={onSubmit}
                  className="flex items-center gap-2 bg-primary hover:bg-indigo-700 text-white px-6 py-2 rounded-lg shadow-md shadow-primary/20 transition-all font-bold"
                >
                  <CheckCircle size={18} />
                  提交试卷
                </button>
              ) : (
                <button
                  disabled={activeQuestionIndex === quiz.questions.length - 1}
                  onClick={() => onQuestionChange(activeQuestionIndex + 1)}
                  className="flex items-center gap-2 bg-white border border-slate-200 hover:border-primary text-slate-700 hover:text-primary px-6 py-2 rounded-lg shadow-sm transition-all font-medium disabled:opacity-30 disabled:hover:border-slate-200 disabled:hover:text-slate-700"
                >
                  下一题 <ChevronRight size={16} />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
};